package com.dlyk.config.handler;

import com.dlyk.constant.Constants;
import com.dlyk.manager.RedisStringManager;
import com.dlyk.model.User;
import com.dlyk.result.CodeEnum;
import com.dlyk.result.R;
import com.dlyk.util.JSONUtils;
import com.dlyk.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 退出成功处理器
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisStringManager redisStringManager;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 通过认证信息获取用户
        User user = (User) authentication.getPrincipal();

        // 删除redis中用户的token
        Boolean removeResult = redisStringManager.removeValue(Constants.REDIS_JWT_KEY + user.getId());

        // 判断redis中的token是否删除成功
        if (removeResult) {
            // 要返回给前端的数据
            R result = R.OK(CodeEnum.USER_LOGOUT);
            // 将R对象转成json
            String resultJson = JSONUtils.toJSON(result);
            // 将结果返回给前端
            ResponseUtils.write(response, resultJson);
        } else {
            // 要返回给前端的数据
            R result = R.FAIL(CodeEnum.REDIS_TOKEN_DELETE_FAIL);
            // 将R对象转成json
            String resultJson = JSONUtils.toJSON(result);
            // 将结果返回给前端
            ResponseUtils.write(response, resultJson);
        }
    }

}

